<script setup lang="ts">
import type { CollapseModelValue } from 'element-plus';

import type { Ref } from 'vue';

import {
  inject,
  nextTick,
  onBeforeMount,
  onBeforeUnmount,
  onMounted,
  reactive,
  ref,
  watch,
} from 'vue';

import {
  ElCheck,
  ElClose,
  ElEdit,
  ElInfoFilled,
  ElLocation,
  ElTickets,
} from '@vben/icons';

import {
  ElCheckbox,
  ElCol,
  ElCollapse,
  ElCollapseItem,
  ElDescriptions,
  ElDescriptionsItem,
  ElIcon,
  ElInput,
  ElInputNumber,
  ElRow,
  ElSwitch,
  ElTable,
  ElTableColumn,
  ElTag,
  ElTooltip,
} from 'element-plus';

import { usePublicStore, useSceneStore } from '#/store';

interface LayerDescriptionItem {
  id: string;
  description: string;
  isEditing: boolean;
}
const emits = defineEmits(['confirmBtnAvalible']);
// interface LayerDescription {
//   [key: string]: LayerDescriptionItem
// }

const sceneStore = useSceneStore();
const publicStore = usePublicStore();
const currentLayer = inject('currentSelectedLayer') as any;
const isDragging: Ref<Boolean> = inject('isDragging', ref(false));
const activeNames = ref(['chartParams']);
const isPreview = ref(false);
const tableRef = ref();
const moreIconShow = ref(false);
const currentSource = ref();
const layerDescriptions = ref<LayerDescriptionItem[]>([]);
const loop = ref(false);
const fitExtent = ref(false);
const isAnimationOpen = ref(false);
const timeInterval = ref(500);
const animationRenderParams = reactive({
  layer: currentLayer.value,
  isAnimationOpen,
  playOptions: {
    timeInterval,
    loop,
    fitExtent,
  },
  layerDescriptions,
} as any);

const renderType = [
  {
    value: 'singleValueRender',
    label: '单一值',
  },
  {
    value: 'uniqueValueRender',
    label: '唯一值',
  },
  {
    value: 'hierarchicalRender',
    label: '等级',
  },
  {
    value: 'gradualValueRender',
    label: '渐变',
  },
  {
    value: 'heatMap',
    label: '热力图',
  },
  {
    value: 'cluster',
    label: '聚合图',
  },
  {
    value: 'pie',
    label: '饼图',
  },
  {
    value: 'bar',
    label: '柱状图',
  },
  {
    value: 'singleBandRasterRender',
    label: '单波段',
  },
  {
    value: 'multiBandRasterRender',
    label: '多波段',
  },
];

const renderParamsReturn = () => {
  const { renderParams } = currentLayer.value;
  if (!renderParams) return;
  isAnimationOpen.value = renderParams.isAnimationOpen;
  timeInterval.value = renderParams.timeInterval;
  loop.value = renderParams.loop;
  fitExtent.value = renderParams.fitExtent;
  layerDescriptions.value = renderParams.layerDescriptions;
};

const getSourceById = (id: any) => {
  return sceneStore.currentSceneConfig.sources.find(
    (item: any) => item.sourceId === id,
  );
};

const getGeoType = (value: string) => {
  switch (value) {
    case 'LINESTRING':
    case 'MULTILINESTRING': {
      return '线';
    }
    case 'MULTIPOINT':
    case 'POINT': {
      return '点';
    }
    case 'MULTIPOLYGON':
    case 'POLYGON': {
      return '面';
    }
    default: {
      return '未知';
    }
  }
};

const getRasterType = (fileType: string) => {
  switch (fileType) {
    case 'jpg':
    case 'png': {
      return '图片';
    }
    case 'tif':
    case 'tiff': {
      return '影像';
    }
    default: {
      return '未知';
    }
  }
};

const getRenderLabel = (type: string) => {
  return renderType.find((item: any) => item.value === type)?.label;
};

const handlePanelChange = (panelName: CollapseModelValue) => {
  if (panelName !== 'chartParams') {
    isPreview.value = false;
  }
};

const handleMouseOver = (
  _row: any,
  _column: any,
  _cell: HTMLTableCellElement,
  _event: Event,
) => {
  // console.log(row, column, cell, event);

  moreIconShow.value = true;
};

const rowClick = (row: any) => {
  tableRef.value.toggleRowExpansion(row);
};

const editLayerDescription = (layerId: string) => {
  layerDescriptions.value.find(
    (item: LayerDescriptionItem) => item.id === layerId,
  )!.isEditing = true;
  nextTick(() => {
    const renameInput = document.querySelector('#editing') as any;
    // console.log('dom', input);
    renameInput.focus();
  });
};

const getLayerDescriptionItem = (layerId: any) => {
  return layerDescriptions.value.find(
    (item: LayerDescriptionItem) => item.id === layerId,
  );
};

const initLayerDescription = () => {
  // layerDescriptions.value = currentLayer.value.layers.map((item: any) => ({ [item.id]: { description: '', isEditing: false } }))
  currentLayer.value.layers.forEach((item: any) => {
    layerDescriptions.value.push({
      id: item.id,
      description: '暂未添加描述',
      isEditing: false,
    });
  });
};

const saveLayerDescription = () => {
  // console.log(layerDescriptions.value);
};
watch(
  () => isAnimationOpen.value,
  (newVal) => {
    emits('confirmBtnAvalible', newVal);
  },
);
watch(
  animationRenderParams,
  () => {
    publicStore.setRenderOptions(animationRenderParams);
  },
  {
    immediate: true,
    deep: true,
  },
);
watch(
  () => isDragging.value,
  (newVal) => {
    if (newVal) {
      isPreview.value = false;
    }
  },
);
//
onBeforeMount(() => {
  initLayerDescription();

  // nextTick()
});
onMounted(async () => {
  if (!isAnimationOpen.value) {
    emits('confirmBtnAvalible', false);
  }
  currentSource.value = getSourceById(currentLayer.value.layers[0].source);
  renderParamsReturn();
});
onBeforeUnmount(() => {
  isPreview.value = false;
});
</script>

<template>
  <div class="all">
    <ElRow class="itemRow" style="display: flex; align-items: center">
      <span class="label-style"> 图层列表： </span>
      <ElTooltip effect="dark" content="动画播放的图层列表" placement="right">
        <ElIcon size="14px" class="icon-style">
          <ElInfoFilled />
        </ElIcon>
      </ElTooltip>
    </ElRow>
    <ElRow class="itemRow layer-info">
      <ElCol :span="24">
        <ElTable
          ref="tableRef"
          :data="currentLayer.layers"
          style="width: 100%"
          max-height="200"
          @cell-mouse-enter="handleMouseOver"
          @row-click="rowClick"
        >
          <ElTableColumn type="expand" width="25">
            <template #default="props">
              <!-- <div class="expand-info">
                <div style="display: flex;justify-content: space-between">
                  <span>名称: {{ props.row.name }}</span>
                  <span>类型: {{ props.row.type }}</span>
                </div>
              </div> -->
              <ElDescriptions
                style="padding: 0 5px"
                :column="1"
                border
                class="expand-info"
              >
                <template #title>
                  <span>图层描述</span>
                  <ElTooltip
                    effect="dark"
                    content="添加描述在动画轮播时展示"
                    placement="right"
                  >
                    <ElIcon size="13" class="icon-style">
                      <ElInfoFilled />
                    </ElIcon>
                  </ElTooltip>
                </template>
                <template #extra>
                  <ElTooltip effect="dark" content="编辑" placement="top">
                    <ElIcon
                      size="13"
                      @click="editLayerDescription(props.row.id)"
                      class="icon-style"
                    >
                      <ElEdit />
                    </ElIcon>
                  </ElTooltip>
                </template>
                <ElDescriptionsItem label="名称" align="center" :min-width="90">
                  <span class="detail-info-item">{{ props.row.name }}</span>
                </ElDescriptionsItem>
                <ElDescriptionsItem align="center">
                  <template #label>
                    <div class="cell-item">
                      <ElIcon size="12" style="margin-right: 2px">
                        <ElLocation />
                      </ElIcon>
                      范围
                    </div>
                  </template>
                  18100000000
                </ElDescriptionsItem>
                <ElDescriptionsItem align="center">
                  <template #label>
                    <div class="cell-item">
                      <ElIcon size="12" style="margin-right: 2px">
                        <ElTickets />
                      </ElIcon>
                      描述
                    </div>
                  </template>
                  <span
                    class="detail-info-item"
                    v-if="!getLayerDescriptionItem(props.row.id)?.isEditing"
                  >
                    {{ getLayerDescriptionItem(props.row.id)?.description }}
                  </span>
                  <ElInput
                    class="editing-input"
                    v-else
                    v-model="getLayerDescriptionItem(props.row.id)!.description"
                    clearable
                    @blur="
                      getLayerDescriptionItem(props.row.id)!.isEditing = false
                    "
                    id="editing"
                    @change="saveLayerDescription"
                  />
                </ElDescriptionsItem>
              </ElDescriptions>
            </template>
          </ElTableColumn>
          <ElTableColumn
            label="图层"
            prop="name"
            width="190"
            show-overflow-tooltip
          />
          <ElTableColumn prop="uniqueValue" label="类型" width="150">
            <template #default="scope">
              <ElTag
                disable-transitions
                effect="plain"
                v-if="getSourceById(scope.row.source).geoType"
              >
                {{ getGeoType(getSourceById(scope.row.source).geoType) }}
              </ElTag>
              <ElTag disable-transitions effect="plain" v-else>
                {{ getRasterType(getSourceById(scope.row.source).fileType) }}
              </ElTag>
            </template>
          </ElTableColumn>
          <ElTableColumn label="渲染方式" width="150">
            <template #default="scope">
              <ElTag type="success" effect="plain" disable-transitions>
                {{ getRenderLabel(scope.row.renderType[1]) }}
              </ElTag>
            </template>
          </ElTableColumn>
          <!-- <el-table-column width="35">
            <template #default="scope">
              <div class="more-icon" @mouseover="handleMouseOver" v-show="moreIconShow">
                <el-icon>
                  <MoreFilled />
                </el-icon>
              </div>
            </template>
          </el-table-column> -->
        </ElTable>
      </ElCol>
    </ElRow>
    <ElRow class="itemRow">
      <ElCol :span="24">
        <ElCollapse v-model="activeNames" accordion @change="handlePanelChange">
          <ElCollapseItem title="播放参数" name="chartParams">
            <ElRow class="itemRow">
              <ElCol :span="5" style="display: flex; align-items: center">
                <span class="label-style"> 是否开启： </span>
              </ElCol>
              <ElCol :span="19">
                <ElSwitch
                  v-model="isAnimationOpen"
                  inline-prompt
                  :active-icon="ElCheck"
                  :inactive-icon="ElClose"
                  size="default"
                />
              </ElCol>
            </ElRow>
            <ElRow class="itemRow">
              <ElCol :span="5">
                <span class="label-style"> 间隔时间： </span>
              </ElCol>
              <ElCol :span="8" class="define-input-number">
                <ElInputNumber
                  :disabled="!isAnimationOpen"
                  v-model="timeInterval"
                  :min="100"
                  :max="3000"
                  :step="100"
                  controls-position="right"
                />
              </ElCol>
              <ElCol :span="5" class="define-checkbox">
                <ElCheckbox
                  :disabled="!isAnimationOpen"
                  v-model="loop"
                  label="循环播放"
                  size="large"
                />
              </ElCol>
              <ElCol :span="6" class="define-checkbox">
                <ElCheckbox
                  :disabled="!isAnimationOpen"
                  v-model="fitExtent"
                  label="适应图层范围"
                  size="large"
                />&nbsp;
                <ElTooltip
                  effect="dark"
                  content="切换图层时是否缩放至图层范围"
                  placement="right"
                >
                  <ElIcon size="14px" class="icon-style">
                    <ElInfoFilled />
                  </ElIcon>
                </ElTooltip>
              </ElCol>
            </ElRow>
          </ElCollapseItem>
        </ElCollapse>
      </ElCol>
    </ElRow>
  </div>
</template>
<style scoped>
.all {
  width: 100%;
}

.itemRow {
  width: 100%;
  padding: 5px;
}

.el-input {
  width: 100%;
}

.label-style {
  font-size: 15px;
}

.colorInput {
  caret-color: transparent;
}

:deep(.colorInput .el-input__inner:hover) {
  cursor: pointer;
}

.layer-info {
  height: 200px;
}

.legend {
  margin-top: 2px;
}

:deep(.el-table .el-table__cell:not(.el-table__expanded-cell)) {
  text-align: center;
}

/* 去除表格边框 */
:deep(.el-table:not(.el-table--border) .el-table__cell) {
  border: none;
}

:deep(.el-table--small .cell) {
  /* padding-right: 20px; */
  height: 25px;
}

:deep(.layer-info .el-table--enable-row-hover .el-table__body tr:hover > td) {
  cursor: pointer;
  background-color: rgb(140 182 222 / 20%);
}

/* 高亮选中行 */

/* :deep(.layer-info .el-table .el-table__body tr.current-row>td) {
  background-color: #d9ecff;
} */

:deep(.el-collapse-item__header) {
  font-size: 15px;
  font-weight: 600;
}

.icon-style:hover {
  color: rgb(63 158 255);
  cursor: pointer;
}

/* 自定义input-number后置数字输入框内单位  */
:deep(.define-input-number .el-input-number) {
  position: relative;

  :deep(&::after) {
    position: absolute;
    top: 50%;
    right: 30px;
    display: inline-block;
    width: 20px;
    height: 25px;
    line-height: 20px;
    text-align: center;
    content: 'ms';
    transform: translateY(-50%);
  }
}

:deep(.define-input-number .el-input-number--small) {
  width: 140px;
}

:deep(.define-checkbox .el-checkbox.el-checkbox--large) {
  height: 100%;
}

.expand-info .cell-item {
  display: flex;
  align-items: center;
  justify-content: center;
}

:deep(.el-descriptions--small .el-descriptions__header) {
  margin-bottom: 8px;
  border-left: 4px solid #409eff;
}

.detail-info-item {
  display: block;
  width: 400px;

  /* 禁止换行 */
  overflow: hidden;

  /* 隐藏超出部分 */
  text-overflow: ellipsis;
  white-space: nowrap;

  /* 使用省略号显示超出内容 */
}
</style>
